<?php

namespace My\Model;

use Utuo\UtuoModel;

class ModuleSubscribeModel extends UtuoModel {
	
	protected $_auto = array (
			array('start_time', 'strtotime', self::MODEL_BOTH, 'function'),
			array('end_time', 'strtotime', self::MODEL_BOTH, 'function'),
			array('items', 'getItems', self::MODEL_BOTH, 'callback'),
			array('content','', self::MODEL_BOTH, 'ignore'),
			array('content','htmlspecialchars_decode', self::MODEL_BOTH, 'function'),
			array('result','', self::MODEL_BOTH, 'ignore'),
			array('result','htmlspecialchars_decode', self::MODEL_BOTH, 'function'),
	);
	
	// 表单显示字段与数据配置
	public $items = array (
			"name" => "姓名",
			"tel" => array('title' => "电话", 'category'=>'tel'),
			"address" => "地址",
			"sex" => array('title' => "性别", 'type' => 'select', 'data'=>array('1'=>'男', '0'=>'女'), 'default'=>array(''=>'保密')),
			"idnum" => array('title' => "身份证", 'category'=>'number') ,
			"birthday" => array('title' => "出生日期", 'category'=>'date'),
			"age" => array('title' => "年龄", 'category'=>'number') 
	);
	
	/**
	 * 创建表单字段
	 * @param unknown $d 模型
	 * @param unknown $e 可用字段
	 */
	public function createForm($e) {
		$enable_field = explode(',', $e);
		$form_html = array();
		foreach ($this->items as $k => $v) {
			if(in_array($k, $enable_field)) {
				$type = "input";
				$category = 'text';
				$title = "";
				if(is_string($v)) {
					$title = $v;
				}elseif(is_array($v)) {
					$title = $v['title'];
					empty($v['type']) or $type = $v['type'];
					empty($v['category']) or $category = $v['category'];
				}
				switch ($type) {
					case "input":
						$form_html[] = "<div class=\"clearfix form-item\"><label>{$title}:</label> <div><input name=\"{$k}\" type=\"{$category}\" datatype=\"*\"/></div></div>";
						break;
					case "select":
						$form_html[] = "<div class=\"clearfix form-item\"><label>{$title}:</label> <div><select name=\"{$k}\">";
						$data = array();
						if(is_array($v['default'])) 
							$data = $v['default']; 
						else 
							$data[''] = '==请选择==';
						if($v['data'])  $data = array_merge($data, $v['data']);
						foreach ($data as $k0 => $v0) {
							$form_html[] = "<option value=\"{$k0}\">{$v0}</option>";
						}
						$form_html[] = "</select></div></div>";
						break;
					default:
						break;
				}
			}
		}
		return join("", $form_html);
	}
	
	public function getItems() {
		if(!isset($_REQUEST['items'])) return false;
		$item_new = array();
		$items = I('items');
		$keys = array_keys($this->items);
		foreach (explode(',', $items) as $v){
			if(in_array($v, $keys)){
				$item_new[] = $v;
			}
		}
		return join(',', $item_new);
	}
	
}
